#include "LevelGenerator.h"
#include "Block.h"

LevelGenerator* LevelGenerator::_levelGenerator = NULL;

LevelGenerator* LevelGenerator::GetInstance()
{
	if (_levelGenerator == NULL)
	{
		_levelGenerator = new LevelGenerator();
	}

	return _levelGenerator;
}

void LevelGenerator::DestroyInstance()
{
	if (_levelGenerator != NULL)
	{
		free(_levelGenerator);
	}
}

void LevelGenerator::GenerateBlocks(Player *player, std::vector<Block> &blocks)
{
	Vector2 blockWallPosition = Vector2((player->GetPlayerIndex() -1) * (6 * Block::BlockWidth()) , 480 - (9 * Block::BlockWidth()));
	int i = 54; // max blocks 0 -- 53 -> 54 blocks
	for (int l = 0; l < 9; l++)
	{
		for (int c = 0; c < 6; c++)
		{
			Block block =  Block();
			block.SetPosition(Vector2(blockWallPosition.X + c * block.BlockWidth(),
				blockWallPosition.Y + l * block.BlockWidth()));
			block.myIndex = i;

			blocks.insert(blocks.begin(),block); // always insert into the top of the queue, because of that I need to start with the max

			i--;
		}
		
	}
}

bool LevelGenerator::IsChosenColor(LevelGenerator::BlockColor blockColor)
{
	for (int i = 0; i < chosenColors.size(); i++)
	{
		if (chosenColors.at(i) == blockColor)
		{
			return true;
		}
	}

	return false;
}

LevelGenerator::BlockColor LevelGenerator::RandomBlockColor()
{
	int enumLength = LevelGenerator::COUNT;

	int indexColor = (int)(std::rand() % enumLength);

	return LevelGenerator::Black;
}

LevelGenerator::BlockColor LevelGenerator::RaffleColor()
{
	LevelGenerator::BlockColor blockColor = LevelGenerator::COUNT;
	do 
	{
		blockColor = RandomBlockColor();

	}
	while (IsChosenColor(blockColor));

	return blockColor;
}



Scene *LevelGenerator::CreateScene(int amountPlayers, ALLEGRO_BITMAP* background)
{
	Scene *scene = new Scene();
	scene->SetImage(background);

	for (int i = 0; i < amountPlayers; i++)
	{
		Player player = Player();
		player.SetPlayerIndex(i + 1);

		std::vector<Block> blocks;
		GenerateBlocks(&player, blocks);

		scene->blocks[player] = blocks;
	}

	return scene;
}